package com.simple.modules.sys.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.simple.common.utils.Constant;
import com.simple.modules.sys.dao.SysMenuDao;
import com.simple.modules.sys.entity.SysMenuEntity;
import com.simple.modules.sys.service.SysMenuService;
import com.simple.modules.sys.service.SysRoleMenuService;
import com.simple.modules.sys.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;

@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuDao, SysMenuEntity> implements SysMenuService {
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysRoleMenuService sysRoleMenuService;
	
	@Override
	public List<SysMenuEntity> queryListParentId(Integer parentId, List<Integer> menuIdList) {
		List<SysMenuEntity> menuList = queryListParentId(parentId);
		if(menuIdList == null){
			return menuList;
		}
		
		List<SysMenuEntity> userMenuList = new ArrayList<>();
		for(SysMenuEntity menu : menuList){
			if(menuIdList.contains(menu.getMenuId())){
				userMenuList.add(menu);
			}
		}
		return userMenuList;
	}

	@Override
	public List<SysMenuEntity> queryListParentId(Integer parentId) {
		return baseMapper.queryListParentId(parentId);
	}

	@Override
	public List<SysMenuEntity> queryNotButtonList() {
		return baseMapper.queryNotButtonList();
	}

	@Override
	public List<SysMenuEntity> getUserMenuList(Long userId) {
		//用户菜单列表
		List<Integer> menuIdList = sysUserService.queryAllMenuId(userId);
		if (menuIdList.isEmpty()){
			return new ArrayList<>();
		}
		Collection<SysMenuEntity> sysMenuEntities = listByIds(menuIdList);
		List<SysMenuEntity> resultList = new ArrayList<>(sysMenuEntities);
		resultList.sort(Comparator.comparingInt(SysMenuEntity::getOrderNum));
		return resultList;
	}

	@Override
	public void delete(Integer menuId){
		//删除菜单
		removeById(menuId);
		//删除菜单与角色关联
		sysRoleMenuService.deleteByMenuId(menuId);
	}

	/**
	 * 递归
	 */
	private List<SysMenuEntity> getMenuTreeList(List<SysMenuEntity> menuList, List<Integer> menuIdList){
		List<SysMenuEntity> subMenuList = new ArrayList<>();
		
		for(SysMenuEntity entity : menuList){
			//目录
			if(entity.getType() == Constant.MenuType.CATALOG.getValue()){
				entity.setList(getMenuTreeList(queryListParentId(entity.getMenuId(), menuIdList), menuIdList));
			}
			subMenuList.add(entity);
		}
		
		return subMenuList;
	}
}
